import { Ref, computed, defineComponent, onMounted, reactive, ref } from "vue";
import classes from "./index.module.scss"
import { useEmiter } from "@/hooks/useEmiter";
import { useTable } from "@/hooks/useTable";
import { WorkArea } from "@/components/WorkArea";
import Table, { GridType } from "@/components/Table";
import { ConditionItemType, ToolsItemType } from "@/hooks/useElementFormItem";
import { onEnterKeydown } from "@/hoc/onEnterDown";
import apiStore from "@/stores/apiStore";
import { changeDataMutual, debounce, getLinkedListValue, isSuccessCode, joinMacrotask, joinMicrotask, useElMessageBox } from "@Tea/utils";
import {  MenuFormParam, MenuItemType, } from "@Tea/model";
import { MenuDialog, MenuTitleType } from "./module/add-dialog";
import { useRoute } from "vue-router";
import routerStore from "@/stores/routerStore";
import TableV2, { TableV2Type } from "@/components/TableV2";
import { useTableV2 } from "@/hooks/useTableV2";
import { httpCommonHandle } from "@/utils/httpUtils";
import { RouteType } from "@/types/router";

export default defineComponent({
  name: "menuManage",
  setup(props, ctx) {
    const { tableName } = useEmiter("menuManage")
    const {
      mountSearch, tableLoading,handleRadioRow,
      setRowData,commonSearch,
      setAllTreeExpand,clearTreeExpand
    } = useTableV2(tableName)
    const { getSystemMenu,deleteMenu ,putMenuState} = apiStore().api

    // 是否展示 dia-log
    const visible = ref(false)
    const menuTitle: Ref<MenuTitleType> = ref("新增菜单")

    // table配置
    const table: TableV2Type["tableConfig"] = reactive({
      data: [],
      rowConfig: { keyField: "code" },
      treeConfig: {
        transform: true, rowField: 'menuId', parentField: 'pMenuId', expandRowKeys: ["base-web"]
      },
      radioConfig: { labelField: "code", highlight: true }
    })
    // colmun 配置
    const colmun: TableV2Type["colmunConfig"] = [
      { field: "code", type:"radio", title: "菜单编码", treeNode: true },
      { field: "title", title: "菜单名称" },
      { field: "menuIndex", title: "菜单序号",width:75 },
      { field: "creator", title: "创建人", width: 100 },
      { field: "createTime", title: "创建时间", width: 200 },
    ]

    // 搜索条件
    const searchForm = reactive({
      enable: 1
    })

    // 禁用启用的标识
    const handleStateFlag = computed(() => {
      return searchForm.enable ? '停用' : '启用'
    })

    // 全选或者反选
    const isSelectAll = ref(true)
    // 全选或者反选的标识
    const selectFlag = computed(()=> isSelectAll.value ? '全部打开' :'全部关闭')

    // 表单对象
    const ruleForm: MenuItemType = reactive({
      code: "",
      title: "",
      pMenuId: 0,
      menuIndex: 0
    } as MenuItemType)

    // 当前选择
    const targetRow :MenuItemType= {
      code: "",
      title: "",
      pMenuId: 0,
      menuId: 0,
      menuIndex: 0,
    }

    /**
     * @use 新增菜单
     */
    const addMenu = async () => {
      handleRadioRow<MenuItemType>((data) => {
        delete ruleForm.menuId
        changeDataMutual(ruleForm, {
          code: "",
          title: "",
          pMenuId: data.menuId,
          menuIndex: 0
        } as MenuItemType)
        
        changeDataMutual(targetRow, data)

        visible.value = true
        menuTitle.value = "新增菜单"
        delete ruleForm.menuId
      })
    };

    /**
     * @use 编辑菜单
     */
    const editMenu = async () => {
      handleRadioRow<MenuItemType>((data) => {
        ruleForm.menuId = 0
        changeDataMutual(ruleForm, data)
        changeDataMutual(targetRow, data)
        visible.value = true
        menuTitle.value = "编辑菜单"
      })
    }

    /**
     * @use 删除菜单
     */
    const handleDelete = () => {
      handleRadioRow<RouteType>((data) => {
        const menuIds = [data.menuId, ...getLinkedListValue<RouteType>(data.children, "menuId", "children")] as RouteType["menuId"][]
        useElMessageBox({
          content: `执行此操作将会删除当前菜单 ${data.title} 以及其有关的字段,确定要继续吗？`,
          thenCallback: () => {
            httpCommonHandle({
              loading: tableLoading,
              callBack:() => deleteMenu (menuIds),
              onSuccess: searchData
            })
          }
        })
      })
    }

    /**
     * @use 改变状态
     */
    const handleState = async () => {
      handleRadioRow<RouteType>((data) => {
        const menuIds = [data.menuId, ...getLinkedListValue<RouteType>(data.children, "menuId", "children")] as RouteType["menuId"][]
        
        useElMessageBox({
          content: `确定要${handleStateFlag.value}吗？`,
          thenCallback: () => {
            httpCommonHandle({
              loading: tableLoading,
              callBack:() => putMenuState({
                menuIds,
                enable: searchForm.enable === 1 ? 0 : 1
              }),
              onSuccess: searchData
            })
          }
        })
      })
    }

    // 打开或者关闭
    const closeOrOpenTree = () => {
      isSelectAll.value ? setAllTreeExpand() : clearTreeExpand()
      isSelectAll.value = !isSelectAll.value
    }

    /**
     * @use 查询
     */
    const searchData = async () => {
      commonSearch(getSystemMenu(searchForm))
    }
    
    // 创建工具的配置
    const toolsList: ToolsItemType<typeof searchForm>[] = [
      {
        type: "button", content: "新增" , attr: {
          onClick: addMenu
        }
      },
      {
        type: "button", content: "编辑" , attr: {
          onClick: editMenu
        }
      },
      {
        type: "button", content: "删除" , attr: {
          onClick: handleDelete
        }
      },
      {
        type: "button", content: handleStateFlag , attr: {
          onClick: handleState
        }
      },
      {
        type: "button", content: selectFlag , attr: {
          onClick: () => closeOrOpenTree()
        }
      },
      {
        type: "button", content: "查询" , attr: {
          onClick: debounce(searchData, 200) 
        }
      },
      {
        type: "checkbox",
        optionLabel: computed(() => {
          return searchForm.enable ? '启用' :'停用'
        }),
        feild:"enable",
        attr: {
          'true-label': 1,
          'false-label': 0,
          onChange: () => {
            isSelectAll.value = true;
            searchData()
          }
        },
        vModel: searchForm
      }
    ]

    const onHandleSuccess = () => {
      visible.value = false
      searchData()
    }

    // 生命周期
    onMounted(() => {
      searchData()
    })

    return () => (
      <section class={`${classes.userList} m-padding m-fullBox m-window`}>
        <MenuDialog
          visible={visible}
          title={menuTitle.value}
          ruleForm={ruleForm}
          targetRow={targetRow}
          handleSuccess={onHandleSuccess}
        />
        <WorkArea
          tools={toolsList}
          onSearch={searchData}
          /
        >
        <TableV2
          v-loading={tableLoading.value}
          vexTableV2={{
            tableConfig: table,
            colmunConfig: colmun
          }}
          initPagination={false}
          tableName={tableName}
          /
        >
      </section>
    )
  },
})